package cn.murky.admin.system.biz.mq;

import cn.murky.admin.system.biz.domain.entity.SysNotice;
import cn.murky.admin.system.biz.endpoint.NoticeEndpoint;
import cn.murky.folkmq.constant.SysGroupConstant;
import cn.murky.folkmq.utils.MurkyMqUtils;
import lombok.extern.slf4j.Slf4j;
import org.noear.redisx.RedisClient;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.cloud.CloudEventHandler;
import org.noear.solon.cloud.annotation.CloudEvent;
import org.noear.solon.cloud.model.Event;


import static cn.murky.folkmq.constant.SysTopicConstant.SYS_NOTICE_TOPIC;

@Component
@Slf4j
@CloudEvent(topic = SYS_NOTICE_TOPIC + 0, group = SysGroupConstant.DEFAULT)
public class SysNoticeMqTemplate implements CloudEventHandler {
    @Inject
    private RedisClient redisClient;
    @Inject
    private NoticeEndpoint noticeEndpoint;

    public void publish(SysNotice sysNotice) {
        Event event = new Event(SYS_NOTICE_TOPIC + sysNotice.getTarget().getCode(), ONode.stringify(sysNotice))
                .group(SysGroupConstant.DEFAULT);
        MurkyMqUtils.publish(event);
    }

    @Override
    public boolean handle(Event event) throws Throwable {
        log.info("[SysNoticeMqTemplate] -> 消费系统通知消息 -> topic:{},msg:{}", event.topic(), event.content());
        boolean lock = redisClient.getLock(event.topic() + "LOCK").tryLock(5);
        // 分布式锁,在集群环境下防止重复刷新缓存
        if(lock){
            SysNotice sysNotice = ONode.deserialize(event.content(), SysNotice.class);
            noticeEndpoint.sendSysNotice(sysNotice);
        }
        return true;
    }
}
